package bpay

import (
	"context"
	"fmt"

	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/pay/base"
	"gitee.com/liuxuezhan/ar-platform/pay-channel-packet/bpay/bpay"
)

type Factory struct {
}

func (p *Factory) CreatePay(config base.Config) base.Payment {
	return &Bpay{
		SecretKey:  config.SecretKey,
		Url:        config.Url,
		ReturnUrl:  config.ReturnUrl,
		NotifyUrl:  config.NotifyUrl,
		MerchantId: config.MerchantId,
	}
}

type Bpay struct {
	SecretKey  string
	Url        string
	ReturnUrl  string
	NotifyUrl  string
	MerchantId string
}

// 代付订单创建
func (B *Bpay) Withdraw(ctx context.Context, req map[string]any) (resp base.WithdrawRes, err error) {
	// 请求第三方接口
	mid := B.MerchantId
	orderid := req["Order"].(map[string]any)["OrderNo"].(string)
	title := req["Order"].(map[string]any)["OrderNo"].(string)
	bankName := ""
	bankCardNo := ""
	bankUser := ""
	bankBranch := ""
	if _, exists := req["Order"].(map[string]any)["UserBank"]; exists {
		bankName = req["Order"].(map[string]any)["UserBank"].(map[string]any)["BankName"].(string)
		bankCardNo = req["Order"].(map[string]any)["UserBank"].(map[string]any)["CardNumber"].(string)
		bankUser = req["Order"].(map[string]any)["UserBank"].(map[string]any)["UserName"].(string)
		bankBranch = req["Order"].(map[string]any)["UserBank"].(map[string]any)["IfscCode"].(string)
	}
	amount := fmt.Sprintf("%.2f", req["Order"].(map[string]any)["OrderAmount"])
	url := B.Url + "/payout/json2"
	_, err = bpay.Withdraw(url, mid, orderid, amount, title, bankName, bankCardNo, bankUser, bankBranch, B.NotifyUrl, B.SecretKey)
	if err != nil {
		return resp, err
	} else {
		resp = base.WithdrawRes{
			OrderSn:      req["Order"].(map[string]any)["OrderNo"].(string),
			ThirdOrderSn: "",
		}
		return resp, err
	}
}
